package J20241104_high_precision;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 高精度减法
 * User: 王圆豪
 * Date: 2024-11-04
 * Time: 22:04
 */
public class High_precision_subtraction {
    public static void main(String[] args) {
        String s1 = "1502";
        String s2 = "552";

        int[] arr1 = new int[s1.length()];
        int[] arr2 = new int[s2.length()];

        for (int i = s1.length() - 1; i > -1; i--) {
            arr1[s1.length() - i - 1] = s1.charAt(i) - '0';
        }
        for (int i = s2.length() - 1; i > -1; i--) {
            arr2[s2.length() - i - 1] = s2.charAt(i) - '0';
        }


        List<Integer> arr = sub(arr1.length >= arr2.length ? arr1 : arr2, arr1.length >= arr2.length ? arr2 : arr1);
        Collections.reverse(arr);

//        System.out.println(Arrays.toString(arr1));
        System.out.println(arr.toString());
    }

    private static List<Integer> sub(int[] arr1, int[] arr2) {
        List<Integer> arr = new ArrayList<>();
        int t = 0;

        for (int i = 0; i < arr1.length; i++) {
            if (i < arr2.length) t = arr1[i] - arr2[i] - t;
            else t = arr1[i] - t;
            arr.add((t + 10) % 10);
            t = t < 0 ? 1 : 0;
        }

        for (int i = arr.size() - 1; i > 0; i--) {
            if (arr.get(i) == 0) arr.remove(i);
            else break;
        }

        return arr;
    }
}
